/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.core;

import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.code.motoo.filter.DefaultFilterChain;
import com.google.code.motoo.filter.DefaultIoFilterChain;
import com.google.code.motoo.filter.FilterChain;
import com.google.code.motoo.utils.IoSessionUtils;

/**
 * 
 * @author linfengqi
 * @version 1.0  May 13, 2009
 */
public class DefaultIoSession implements IoSession {
	private SocketChannel channel;
	private long creationTime;
	private long lastAccessTime;
	private IoHandler ioHandler;
	private CopyOnWriteArrayList<IoSessionListener> sessionListeners;
	private FilterChain filterChain = new DefaultFilterChain();
	private IoBuffer ioBuffer;
	public final static int BLOCK = 1024;
	private ConcurrentMap<Object, Object> attribute = new ConcurrentHashMap<Object, Object>();
	public final static Log log = LogFactory.getLog(DefaultIoSession.class);
	
	public DefaultIoSession(SocketChannel channel, IoHandler ioHandler) {
		this.channel = channel;
		this.ioHandler = ioHandler;
		creationTime = System.currentTimeMillis();
		ioBuffer = IoBuffer.allocate(BLOCK, true);
		addAttributes();
	}
	
	private void addAttributes() {
		attribute.put(IO_FILTER_CHAIN, new DefaultIoFilterChain(this));
	}

	public void close(boolean immediately) {
		close();
	}

	public synchronized void close(){
		if (!channel.isOpen())
			return;
		if (channel.isOpen()) {
			try {
				channel.close();
			} catch (Exception e) {
				log.fatal(e);
			}
		}
		try {
			ioHandler.sessionClosed(this);
			
			for (IoSessionListener listener : sessionListeners) {
				listener.closed(this);
            }
			
			IoSessionUtils.removeIoSession(channel);
			
		} catch (Exception e) {
			try {
				ioHandler.exceptionCaught(this, e);
			} catch (Exception e1) {
				log.fatal(e1);
			}
		}
	}
	
	public boolean timeout(long currentTime, long maxIdleTime) {
		if (currentTime - lastAccessTime > maxIdleTime)
			return true;
		return false;
	}

	public long getCreationTime() {
		return creationTime;
	}

	public FilterChain getFilterChain() {
		return filterChain;
	}

	public IoHandler getHandler() {
		return ioHandler;
	}

	public long getLastAccessTime() {
		return lastAccessTime;
	}

	public SocketAddress getLocalAddress() {
		return channel.socket().getLocalSocketAddress();
	}

	public SocketAddress getRemoteAddress() {
		return channel.socket().getRemoteSocketAddress();
	}

	public boolean isClosing() {
		return !channel.isOpen();
	}

	public boolean isConnected() {
		return channel.isConnected();
	}

	public void write(Object message) {
		WriteExecutor writeExecutor = (WriteExecutor) attribute.get(IoSession.WRITE_EXECUTOR);
		writeExecutor.write(this, message);
	}

	public SocketChannel getSocketChannel() {
		return channel;
	}

	public void setLastAccessTime() {
		lastAccessTime = System.currentTimeMillis();
	}

	public IoBuffer getIoBuffer() {
		return ioBuffer;
	}

	public Object getAttribute(Object key) {
		return attribute.get(key);
	}

	public Object setAttribute(Object key, Object value) {
		return attribute.put(key, value);
	}

	public boolean containsAttribute(Object key) {
		return attribute.containsKey(key);
	}

}
